import {
  Mesh,
  BoxGeometry,
  MeshStandardMaterial,
  PerspectiveCamera,
  Scene,
  WebGLRenderer,
  Vector3,
  AmbientLight,
  AxesHelper,
  GridHelper,
} from "three";
import Stats from "three/examples/jsm/libs/stats.module";
import { OrbitControls } from "three/addons";
export class TEngine {
  private dom: HTMLElement;
  private renderer: WebGLRenderer;
  private scene: Scene;
  private camera: PerspectiveCamera;
  constructor(dom: HTMLElement) {
    // 初始化dom
    this.dom = dom;
    // 创建场景
    this.scene = new Scene();
    // 创建相机对象
    this.camera = new PerspectiveCamera(
      45,
      dom.offsetWidth / dom.offsetHeight,
      1,
      1000
    );
    // 设置相机位置
    this.camera.position.set(100, 100, 100);
    // 设置相机方向(指向的场景对象)
    this.camera.lookAt(new Vector3(0, 1, 0));
    // 设置相机角度
    this.camera.up = new Vector3(0, 1, 0);
    // 创建渲染对象
    this.renderer = new WebGLRenderer();
    // 设置渲染尺寸大小
    this.renderer.setSize(dom.offsetWidth, dom.offsetHeight, true);

    // 创建几何体对象
    const box: Mesh = new Mesh(
      new BoxGeometry(10, 10, 10),
      new MeshStandardMaterial({ color: "red", metalness: 0.5 })
    );
    const ambientLight = new AmbientLight("rgb(255,255,255)", 1);
    // 创建坐标轴
    const axesHelper = new AxesHelper(500);
    const gridHelper = new GridHelper(
      500,
      20,
      "rgb(255,255,255)",
      "rgb(100,100,100)"
    );
    // 场景中添加物体
    this.scene.add(box);
    this.scene.add(ambientLight);
    this.scene.add(axesHelper);
    this.scene.add(gridHelper);
    // 设置背景颜色
    // this.renderer.setClearColor('rgb(255,0,0)');
    // 清除颜色
    // this.renderer.clearColor();

    // 初始化性能监视器
    const stats = Stats();
    const statsDom = stats.domElement;
    statsDom.style.position = "fixed";
    statsDom.style.top = "5px";
    statsDom.style.left = "unset";
    statsDom.style.right = "5px";

    // 初始化轨道控制器
    const controls = new OrbitControls(this.camera, this.renderer.domElement);
    controls.enableDamping = true
    const renderFunc = () => {
      box.position.x -= 0.001;
      this.camera.position.x -= 0.001;
      
      controls.update();
      // 执行渲染函数
      this.renderer.render(this.scene, this.camera);
      stats.update();
      // 循环渲染
      requestAnimationFrame(renderFunc);
    };

    renderFunc();
    // 将webgl渲染的canvas内容添加到body
    this.dom.append(this.renderer.domElement);
    this.dom.append(statsDom);
  }
}
